package com.wy.thread_pool.impl;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 一个临时员工要做的工作内容——取任务，执行任务
 **/
public class TemporaryJob implements Runnable{
    //取任务意味着需要阻塞队列
    private final BlockingQueue<Runnable> workQueue;
    private final long keepAliveTime;
    private final TimeUnit unit;
    private Runnable firstCommand;
    TemporaryJob(long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Runnable firstCommand){
        this.keepAliveTime=keepAliveTime;
        this.unit=unit;
        this.workQueue=workQueue;
        this.firstCommand=firstCommand;
    }
    @Override
    public void run() {
        try{
        //优先先把刚提交的任务做完
        firstCommand.run();
        firstCommand=null;//这里设置为null是为了不影响firstCommand对象被GC的回收
        while(true){//或者while(!Thread.interrupted())

            //与正式工的区别—一旦多久没做任务，临时工是会退出的
            //1.keepAliveTime+unit记录起来
            //2.怎么就知道超过多久就没有任务：如果一定时间内都无法从队列中取出任务，就认为摸鱼时间够了
             Runnable command = workQueue.poll(keepAliveTime, unit);
             if(command==null){
                 //说明没有取到任务
                 //说明超时时间已到->说明线程已经keepAliveTime+unit时间没有工作了
                 //所以，可以退出了
                 break;
             }
            command.run();
            }
        }catch (InterruptedException ignored) {}//先不管异常状态
    }
}
